import {getRuntime} from './common';
import Taro, {clearStorage} from "@tarojs/taro";

export interface IShareContent {
  type: 'image' | 'text' | 'canvas';
  url?: string,
  path?: string;
  canvasId?: string;
  text?: string;
  fontSize?: number;
  color?: string;
  textAlign?: string;
  left: number;
  top: number;
  width: number;
  height: number;
}

export const downloadFile = (url, callback: (path) => void) => {
  Taro.downloadFile({
    url,
    success: (res) => {
      callback(res.tempFilePath);
    }
  });
}

export const canvasToTempFilePath = (canvasId, scope, callback: (path) => void) => {
  Taro.canvasToTempFilePath({
    canvasId: canvasId,
    success: function (res) {
      var tempFilePath = res.tempFilePath;
      callback(tempFilePath);
    }
  }, scope);
}

/**
 * initWidth:参照750px的设计尺寸
 */
export const draw = (contrainer, scope, initWidth: number, list: IShareContent[]) => {
  var ctx = Taro.createCanvasContext('shareCanvas', scope);
  Taro.createSelectorQuery().select(contrainer).boundingClientRect(function (rect) {
    Taro.showLoading({
      title: '下载中...'
    });
    var height = rect['height'];
    var width = rect['width'];
    // var left = rect.left * 0.1;
    ctx.setFillStyle('#fff');
    ctx.fillRect(0, 0, width, height);
    ctx.draw();

    const getValue = (value: number) => {
      return width / initWidth * value;
    }
    let array = Array<any>();
    list.map(item => {
      const p = new Promise(resolve => {
        if (item.url) {
          downloadFile(item.url, (path) => {
            item.path = path;
            resolve();
          });
        } else if (item.canvasId) {
          canvasToTempFilePath(item.canvasId, scope, (path) => {
            item.path = path;
            resolve();
          });
        } else {
          resolve();
        }
      });
      array.push(p);
    });

    const plist = Promise.all(array);
    plist.then(() => {
      list.map(item => {
        if (item.type == 'image' || item.type == 'canvas') {
          ctx.drawImage(item.path,
            getValue(item.left),
            getValue(item.top),
            getValue(item.width),
            getValue(item.height)
          );
          // ctx.draw(true);
        } else if (item.type == 'text') {
          ctx.setFontSize(Number(getValue(item.fontSize || 20)));
          ctx.setFillStyle(String(item.color || '#000'));
          ctx.setTextAlign(String(item.textAlign || 'left'));
          ctx.fillText(String(item.text), getValue(item.left), getValue(item.top), getValue(item.width));
          // ctx.draw(true);
        }
      });
      ctx.draw(true, () => {
        Taro.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: function (res) {
            const promise = new Promise(resolve => {
              Taro.hideLoading()
              Taro.getSetting({}).then(res => {
                if (res.authSetting['scope.writePhotosAlbum']) {
                  resolve();
                } else {
                  Taro.authorize({
                    scope: 'scope.writePhotosAlbum'
                  }).then(() => {
                    resolve()
                  }).catch(() => {
                    Taro.hideLoading();
                    //getRuntime().showToast('请授权保存到相册');
                    getRuntime().navigateTo("/pages/user/Wxauth");
                  })
                }
              }).catch((e) => {
                Taro.hideLoading();
                console.log(e)
              })
            });
            promise.then(() => {
              var tempFilePath = res.tempFilePath;
              Taro.saveImageToPhotosAlbum({
                filePath: tempFilePath,
              }).then(() => {
                Taro.hideLoading();
                Taro.showModal({
                  title: '提示',
                  content: '图片已保存到相册，赶紧晒一下吧~',
                  showCancel: false,
                  confirmText: '好的',
                  confirmColor: '#333',
                  success: function (res) {
                    if (res.confirm) {
                    }
                  },
                  fail: function (res) {
                  }
                })
              })
            });
          }
        }, scope);
      });
    })
  }).exec();
}
